package com.mxy.myapplication.activity;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;

import com.mxy.myapplication.R;

import java.lang.ref.WeakReference;

public class SplashActivity extends Activity {

    private View splashimage;
    private static MyHandler myHandler;

    private static class MyHandler extends Handler{

        private static WeakReference<SplashActivity>  slashActivityWeakReference;

        private MyHandler(SplashActivity splashActivity){
            slashActivityWeakReference=new WeakReference<>(splashActivity);
        }

        @Override
        public void handleMessage(Message msg) {
            try{
                SplashActivity splashActivity =slashActivityWeakReference.get();
                if(splashActivity !=null&&!splashActivity.isFinishing()){
                    splashActivity.handleMessage(msg);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    private void handleMessage(Message msg){
        startActivity(new Intent(SplashActivity.this,MainActivity.class));
        finish();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        myHandler=new MyHandler(this);
        setContentView(R.layout.activity_splash);
        splashimage=findViewById(R.id.splashimage);
        showAnimation();
    }

    private void showAnimation(){
        ObjectAnimator rotation=ObjectAnimator.ofFloat(splashimage, "rotation",0f,1080f);
        rotation.setDuration(2000);
        ObjectAnimator alpha=ObjectAnimator.ofFloat(splashimage, "alpha",0f,1f);
        alpha.setDuration(2000);
        ObjectAnimator scaleY=ObjectAnimator.ofFloat(splashimage, "scaleY",0f,1f);
        scaleY.setDuration(2000);
        ObjectAnimator scaleX=ObjectAnimator.ofFloat(splashimage, "scaleX",0f,1f);
        scaleX.setDuration(2000);

        AnimatorSet animatorSet=new AnimatorSet();
        animatorSet.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                myHandler.sendEmptyMessageDelayed(1,500);
            }
        });
        animatorSet.play(rotation).with(alpha).with(scaleY).with(scaleX);
        animatorSet.start();
    }
}